package com.zhentao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.pojo.Menu;
import com.zhentao.service.MenuService;
import com.zhentao.mapper.MenuMapper;
import com.zhentao.util.TreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【Menu】的数据库操作Service实现
* @createDate 2025-07-01 08:55:11
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{
    @Override
    public List<Menu> getMenuTree() {
        // 查询所有菜单
        List<Menu> allMenus = baseMapper.selectList(null);

        // 找出顶级菜单
        List<Menu> rootMenus = allMenus.stream()
                .filter(menu -> menu.getParentid() == 0)
                .collect(Collectors.toList());

        // 递归构建树形结构
        for (Menu menu : rootMenus) {
            menu.setChildren(getChildren(menu.getId(), allMenus));
        }

        return rootMenus;
    }

    @Override
    public List<Menu> getMenuByRole(Integer roleId) {
        // 这里简化处理，实际应根据角色ID查询关联的菜单
        // 此处返回所有菜单，实际项目中需要根据角色权限过滤
        return getMenuTree();
    }

    // 递归获取子菜单
    private List<Menu> getChildren(Integer parentId, List<Menu> allMenus) {
        List<Menu> children = new ArrayList<>();
        for (Menu menu : allMenus) {
            if (menu.getParentid() == parentId) {
                menu.setChildren(getChildren(menu.getId(), allMenus));
                children.add(menu);
            }
        }
        return children;
    }
}




